#!/usr/bin/python3
# -*- coding: utf-8 -*-
# ======================================#
# @Author   : duanqizhong
# @time     : 2021-1-2 23:12
# @file     : parse.py
# @Software : PyCharm
# ======================================#

import os
from configparser import ConfigParser


class ParseConf:
    def __init__(self, path,encode="utf-8"):
        assert os.path.exists(path), f"{path} not found!"
        self.parse = ConfigParser()
        self.parse.read(path,encoding=encode)

    def get_section_options(self, section):
        """获取配置文件内section的options"""
        return self.parse.options(section)

    def check_option(self, section, option):
        """检查是否存在option"""
        if not self.check_section(section):
            return False
        if option in self.get_section_options(section):
            return True
        else:
            return False

    def get_sections(self):
        """获取配置文件内sections"""
        return self.parse.sections()

    def check_section(self, section):
        """检查指定的section是否存在"""
        if section in self.get_sections():
            return True
        else:
            return None

    def get_section_info(self, section):
        """
        获取section的key=value
        default section的值会被获取到，被作为默认值
        如果指定的section不存在，返回{}；否则返回key,value
        """
        section_info = {}
        if self.check_section('default'):
            default_options = self.get_section_options('default')
            for option in default_options:
                section_info[option] = self.parse.get('default', option)
        if section == 'default':
            return section_info
        if self.check_section(section):
            section_options = self.get_section_options(section)
            for option in section_options:
                section_info[option] = self.parse.get(section, option)
        else:
            return {}
        return section_info

    def get_sections_info(self):
        """获取所有sections info，section:{key=value}"""
        sections = self.get_sections()
        sections_info = {}
        for section in sections:
            sections_info[section] = self.get_section_info(section)
        return sections_info

    def get_conn_str(self, section):
        """获取section下的mysql -hhost -Pport -uusername -ppassword字符串"""
        section_info = self.get_section_info(section)
        str = ' -h%s -P%s -u%s -p%s ' % (section_info['host'].strip(),
                                         int(section_info['port'].strip()),
                                         section_info['username'].strip(),
                                         section_info['password'].strip())
        conn_str = 'mysql %s' % str
        dump_str = 'mysqldump %s' % str
        return (conn_str, dump_str)
